<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="24">
          <a-col :xl="24" :lg="24" :md="24" :sm="24" class="title">
            工厂：{{factoryName}}
            <a-divider type="vertical" style="height: 2.9em;"/>
            车间：{{workshopName}}
            <a-divider type="vertical" style="height: 2.9em;"/>
            产线：{{lineName}}
            <a-divider type="vertical" style="height: 2.9em;"/>
            工位：{{stationName}}
          </a-col>
        </a-row>
        <a-row :gutter="24" style="margin-top: 5px;">
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
            <a-form-item label="工厂">
              <j-dict-select-tag placeholder="请选择工厂"
                                 v-model="factoryId"
                                 dictCode="mes_base_factory,factory_name,id,factory_level=1 and factory_status=1"
                                 :use-cache="false"
                                 :disabled="true"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
            <a-form-item label="车间">
              <j-dict-select-tag placeholder="请选择车间"
                                 v-model="workshopId"
                                 dictCode="mes_base_factory,factory_name,id,factory_level=2 and factory_status=1"
                                 :use-cache="false"
                                 :disabled="true"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
            <a-form-item label="产线">
              <j-dict-select-tag placeholder="请选择产线"
                                 v-model="lineId"
                                 dictCode="mes_base_factory,factory_name,id,factory_level=3 and factory_status=1"
                                 :use-cache="false"
                                 :disabled="true"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="6" :md="6" :sm="24">
            <a-form-item label="工位">
              <j-dict-select-tag placeholder="请选择工位"
                                 v-model="stationId"
                                 dictCode="mes_base_factory,factory_name,id,factory_level=4 and factory_status=1"
                                 :use-cache="false"
                                 :disabled="true"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" style="margin-top: 5px;">
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
            <a-form-item label="工单号">
              <span>{{workOrderBarCode}}</span>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" style="margin-top: 5px;" v-if="!finished">
          <a-col :xl="6" :lg="6" :md="6" :sm="24">

          </a-col>
          <template v-if="workOrderBarCode===''">
            <a-col :xl="6" :lg="6" :md="6" :sm="24">
              <a-button type="primary" style="width: 100%;" @click="checkWorkOrder">扫描工单</a-button>
            </a-col>
            <a-col :xl="6" :lg="6" :md="6" :sm="24">
              <a-form-item label="">
                <a-input placeholder="请输入工单条码" v-model.trim="queryParam.workOrderBarCode" @keyup.enter.native="checkWorkOrder"></a-input>
              </a-form-item>
            </a-col>
          </template>
          <template v-if="stationAttribute==='1' || (stationAttribute==='3' && !currentMaterialBtnFinished)" >
            <a-col :xl="6" :lg="6" :md="6" :sm="24">
              <a-button type="primary" style="width: 100%;" @click="checkMaterial">扫描物料号</a-button>
            </a-col>
            <a-col :xl="6" :lg="6" :md="6" :sm="24">
              <a-form-item label="">
                <a-input placeholder="请输入物料号" v-model="queryParam.materialBarCode" @keyup.enter.native="checkMaterial"></a-input>
              </a-form-item>
            </a-col>
          </template>
          <template v-if="stationAttribute==='2' || (stationAttribute==='3' && currentMaterialBtnFinished)">
            <a-col :xl="12" :lg="12" :md="12" :sm="24">
              <a-button type="primary" style="width: 100%;">输入检测值</a-button>
            </a-col>
          </template>
        </a-row>
      </a-form>
    </div>

    <div>
      <a-menu v-model="current" mode="horizontal">
        <a-menu-item key="noFinish" @click="searchNotFinished">
          待完成
        </a-menu-item>
        <a-menu-item key="finished" @click="searchFinished">
          已完成
        </a-menu-item>
        <a-menu-item key="current">
          当前
        </a-menu-item>
      </a-menu>
      <div id="content">
        <div v-show="current.includes('current')">
          <div v-if="stationAttribute==='1'  || stationAttribute==='3'">
            <a-table
              ref="table"
              size="middle"
              :scroll="{x:true}"
              bordered
              rowKey="id"
              :columns="currentMaterialColumns"
              :dataSource="currentMaterialDataSource"
              :loading="currentMaterialLoading"
              :pagination="false"
              class="j-table-force-nowrap">
              <template slot="title">
                <a-row class="j-modal-title-row" type="flex">
                  <a-col class="left">
                    <slot name="title">物料</slot>
                  </a-col>
                </a-row>
              </template>
            </a-table>
            <div class="box" v-if="currentMaterialDataSource.length!==0 && !currentMaterialBtnFinished">
              <a-button type="primary" @click="finishMaterial">完成</a-button>&nbsp;&nbsp;
              <a-button @click="resetMaterial">重置</a-button>
            </div>
          </div>
          <div v-if="stationAttribute==='2' || (currentMaterialBtnFinished && stationAttribute==='3')">
            <a-form layout="inline" class="form">
              <div>
                <a-table
                  ref="table"
                  size="middle"
                  :scroll="{x:true}"
                  bordered
                  rowKey="id"
                  :columns="currentCheckColumns"
                  :dataSource="currentCheckDataSource"
                  :loading="currentCheckLoading"
                  :pagination="false"
                  class="j-table-force-nowrap"
                >
                  <template slot="title">
                    <a-row class="j-modal-title-row" type="flex">
                      <a-col class="left">
                        <slot name="title">检测</slot>
                      </a-col>
                    </a-row>
                  </template>
                  <template slot="value" slot-scope="text, record,index">
                    <a-form-model-item>
                      <a-input-number v-model="record.quantity" :disabled="currentCheckBtnFinished"/>
                    </a-form-model-item>
                  </template>
                  <template slot="radio" slot-scope="text, record,index">
                    <a-form-model-item>
                      <a-radio-group v-model="record.judge" :disabled="currentCheckBtnFinished">
                        <a-radio :value="1">合格</a-radio>
                        <a-radio :value="2">不合格</a-radio>
                      </a-radio-group>
                    </a-form-model-item>
                  </template>
                </a-table>
              </div>
              <div class="box" v-if="currentCheckDataSource.length!==0 && !currentCheckBtnFinished">
                <a-button type="primary" @click="finishCheck">完成</a-button>&nbsp;&nbsp;&nbsp;
                <a-button @click="resetCheck">重置</a-button>
              </div>
            </a-form>
          </div>
        </div>
        <div v-show="current.includes('finished')">
          <production-process-finished ref="finished"></production-process-finished>
        </div>
        <div v-show="current.includes('noFinish')">
          <production-process-not-finished ref="notFinished"></production-process-not-finished>
        </div>
      </div>
    </div>
  </a-card>
</template>

<script>
  import { getAction, postAction } from '@/api/manage'
  import ProductionProcessNotFinished from './modules/ProductionProcessNotFinished.vue';
  import ProductionProcessFinished from './modules/ProductionProcessFinished.vue';




  export default {
    name: 'productionProcess',
    components: {ProductionProcessNotFinished,ProductionProcessFinished},
    data() {
      return {

        current: ['current'],

        factoryId: '',
        factoryName: '',
        workshopId: '',
        workshopName: '',
        lineId: '',
        lineName: '',
        stationId: '',
        stationName: '',
        workOrderId: '',
        workOrderBarCode: '',
        stationAttribute: '',//工位属性
        technologyId: '',
        procedureId: '',
        checkType: '',
        queryParam: {
          workOrderBarCode: '',
          stationAttribute: '',
          materialBarCode: ''
        },
        finished: false,

        url: {
          init: '/mes/productionProcess/initProductionProcess',
          queryWorkOrderByWorkOrderBarCode: '/mes/productionProcess/queryWorkOrderByWorkOrderBarCode',
          materialBomList: '/mes/mesTechnologyProcedureMaterialBom/listNoPage',
          checkBomList: '/mes/mesTechnologyProcedureCheckBom/listNoPage',
          checkMaterialBarCode: '/mes/productionProcess/checkMaterialBarCode',
          finishMaterial: '/mes/productionProcess/finishMaterial',
          finishCheck: '/mes/productionProcess/finishCheck',
        },

        currentMaterialLoading: false,
        currentMaterialColumns: [],
        currentMaterialDataSource: [],
        currentMaterialBtnFinished: false,

        currentCheckLoading: false,
        currentCheckColumns: [],
        currentCheckDataSource: [],
        currentCheckBtnFinished: false,



      }
    },
    created() {
      let that = this
      getAction(this.url.init, {}).then((res) => {
        if (res.success) {
          const result = res.result
          const factory = result['factory']
          const workshop = result['workshop']
          const line = result['line']
          const station = result['station']
          this.factoryId = factory.id
          this.factoryName = factory.factoryName
          this.workshopId = workshop.id
          this.workshopName = workshop.factoryName
          this.lineId = line.id
          this.lineName = line.factoryName
          this.stationId = station.id
          this.stationName = station.factoryName
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    computed: {},
    methods: {
      /**
       * 完成检测
       * */
      finishCheck() {
        for (let i = 0; i < this.currentCheckDataSource.length; i++) {
          let item = this.currentCheckDataSource[i]
          let lowerLimit = item['lowerLimit']
          let upperLimit = item['upperLimit']
          if (!item.quantity || item.quantity === '') {
            this.$message.warning(item.checkItem + '需要填写数值')
            return
          }
          if (lowerLimit && lowerLimit != '' && lowerLimit > item.quantity) {
            this.$message.warning(item.checkItem + '校验值低于设置的最小值（' + lowerLimit + '）')
            return
          }
          if (upperLimit && upperLimit != '' && upperLimit < item.quantity) {
            this.$message.warning(item.checkItem + '校验值高于设置的最大值（' + upperLimit + '）')
            return
          }
          if (this.checkType == '2' && (!item.judge || item.judge === '')) {
            this.$message.warning(item.checkItem + '需要选择判定结果')
            return
          }
        }
        postAction(this.url.finishCheck, {
          procedureId: this.procedureId,
          workOrderBarCode: this.workOrderBarCode,
          list: this.currentCheckDataSource
        }).then((res) => {
          if (res.success) {
            //将【当前】清空
            this.currentCheckBtnFinished = true
            this.finished = true
            //展示【已完成】
            this.current = ['finished']
            this.searchFinished()
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      /**
       * 清空检测项
       * */
      resetCheck() {
        this.currentMaterialLoading = true
        for (let i = 0; i < this.currentMaterialDataSource.length; i++) {
          this.currentMaterialDataSource[i]['quantityFinished'] = 0
          this.currentMaterialDataSource[i]['materialBarCodeList'] = []
        }
        this.currentMaterialLoading = false
        this.currentMaterialBtnFinished = false
      },
      /**
       * 查询未完成的订单列表
       * */
      searchNotFinished() {
        this.$refs.notFinished.show({
          factoryId: this.factoryId,
          workshopId: this.workshopId,
          lineId: this.lineId,
          finishStatus: '1'
        });
      },
      /**
       * 查询已完成的订单列表
       * */
      searchFinished() {
        this.$refs.finished.show({
          factoryId: this.factoryId,
          workshopId: this.workshopId,
          lineId: this.lineId,
          finishStatus: '2'
        });
      },
      /**
       * 重置物料表格
       */
      resetMaterial() {
        this.currentCheckLoading = true
        for (let i = 0; i < this.currentCheckDataSource.length; i++) {
          this.currentCheckDataSource[i]['quantity'] = 0
          if (this.currentCheckDataSource[i]['judge']){
            this.currentCheckDataSource[i]['judge']='';
          }
        }
        this.currentCheckLoading = false
        this.currentCheckBtnFinished = false
      },
      /**
       * 完成物料操作
       */
      finishMaterial() {
        for (let i = 0; i < this.currentMaterialDataSource.length; i++) {
          let item = this.currentMaterialDataSource[i]
          if (item['quantity'] !== item['quantityFinished']) {
            this.$message.warning(item['materialId_dictText'] + '还没有装配完全，请勿操作')
            return
          }
        }
        let params = {
          procedureId: this.procedureId,
          workOrderBarCode: this.workOrderBarCode,
          list: this.currentMaterialDataSource
        }
        postAction(this.url.finishMaterial, params).then((res) => {
          if (res.success) {
            this.currentMaterialBtnFinished = true
            if (this.stationAttribute === '1') {
              this.finished = true
              //展示【已完成】
              this.current = ['finished']
              this.searchFinished()
            } else if (this.stationAttribute === '3') {
              this.initCheck()
            }
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      /**
       * 检查物料号
       * */
      checkMaterial() {
        if (this.queryParam.materialBarCode.trim() === '') {
          this.$message.warning('物料条码为空，请检查')
        }
        //校验物料条码正确性
        let materialSequence = this.queryParam.materialBarCode.substring(0, this.queryParam.materialBarCode.length - 3)
        let flag = false
        for (let i = 0; i < this.currentMaterialDataSource.length; i++) {
          if (this.currentMaterialDataSource[i]['materialId_dictText'] === materialSequence) {
            flag = true
            if (this.currentMaterialDataSource[i]['quantityFinished'] === this.currentMaterialDataSource[i]['quantity']) {
              this.$message.warning('该物料号已满足，请添加其他物料')
              return
            }
            let materialBarCodeList = this.currentMaterialDataSource[i]['materialBarCodeList']
            for (let j = 0; j < materialBarCodeList.length; j++) {
              if (materialBarCodeList[j] === this.queryParam.materialBarCode) {
                this.$message.warning('该物料条码已经扫过，请勿重复操作')
                return
              }
            }
          }
        }
        if (!flag) {
          this.$message.warning('错误的物料条码，请检查')
          return
        }
        //请求
        this.currentMaterialLoading = true
        getAction(this.url.checkMaterialBarCode, {
          materialBarCode: this.queryParam.materialBarCode
        }).then((res) => {
          this.currentMaterialLoading = false
          if (res.success) {
            let materialDetail = res.result
            let materialBarCode = materialDetail.materialBarCode
            let materialSequence = materialBarCode.substring(0, materialBarCode.length - 3)
            let isContain = false
            for (let i = 0; i < this.currentMaterialDataSource.length; i++) {
              if (this.currentMaterialDataSource[i]['materialId_dictText'] === materialSequence) {
                this.currentMaterialDataSource[i]['quantityFinished'] += 1
                this.currentMaterialDataSource[i]['materialBarCodeList'].push(materialBarCode)
                isContain = true
              }
            }
            if (!isContain) {
              this.$message.warning('该物料条码不是所需的物料，请检查后重试')
              return
            }
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      /**
       * 初始化物料列表
       * */
      initMaterial(procedureId) {
        //设置table的头
        this.currentMaterialColumns = [
          {
            title: '物料号',
            align: 'center',
            dataIndex: 'materialId_dictText'
          },
          {
            title: '需求数量',
            align: 'center',
            dataIndex: 'quantity'
          },
          {
            title: '已装配数量',
            align: 'center',
            dataIndex: 'quantityFinished'
          }
        ]
        //发送请求
        this.currentMaterialLoading = true
        getAction(this.url.materialBomList, {
          procedureId: procedureId
        }).then((res) => {
          this.currentMaterialLoading = false
          if (res.success) {
            const result = res.result
            //设置返回数据
            this.currentMaterialDataSource = result.records
            for (let i = 0; i < this.currentMaterialDataSource.length; i++) {
              let item = this.currentMaterialDataSource[i]
              if (this.currentMaterialBtnFinished){
                item['quantityFinished'] = item['quantity']
              } else{
                item['quantityFinished'] = 0
                item['materialBarCodeList'] = []
              }
            }
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      /**
       * 初始化检测属性
       * */
      initCheck() {
        //设置table的头
        let titles = [
          {
            title: '检测项',
            align: 'center',
            dataIndex: 'checkItem'
          },
          {
            title: '数值',
            align: 'center',
            dataIndex: 'quantity',
            scopedSlots: { customRender: 'value' }//表格内容插槽
          }
        ]
        //手动检测需要添加判定列
        if (this.checkType === '2') {
          titles.push({
            title: '判定',
            align: 'center',
            dataIndex: 'judge',
            scopedSlots: { customRender: 'radio' }//表格内容插槽
          })
        }
        this.currentCheckColumns = titles
        //发送请求
        this.currentCheckLoading = true
        getAction(this.url.checkBomList, {
          procedureId: this.procedureId
        }).then((res) => {
          this.currentCheckLoading = false
          if (res.success) {
            const result = res.result
            //设置返回数据
            this.currentCheckDataSource = result.records
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      /**
       * 检查工单号
       * */
      checkWorkOrder() {
        //请求
        getAction(this.url.queryWorkOrderByWorkOrderBarCode, {
          workOrderBarCode: this.queryParam.workOrderBarCode
        }).then((res) => {
          if (res.success) {
            this.workOrderBarCode = this.queryParam.workOrderBarCode
            const result = res.result
            //判断该工单是否已完成--完成跳转已完成|未完成跳转当前
            if (result['workOrderFinishStatus'] === '1') {
              this.current = ['current']
              //未完成
              this.stationAttribute = result.stationAttribute
              this.technologyId = result.technologyId
              this.procedureId = result.id
              this.workOrderId = result.workOrderId
              //判断工位属性
              this.checkType = result.checkType
              if (this.stationAttribute === '1') {
                this.initMaterial(result.id)
              } else if (this.stationAttribute === '2') {
                this.initCheck(result.id, result.checkType)
              } else if (this.stationAttribute === '3') {
                this.initMaterial(result.id)
                if (result.currentMaterialBtnFinished) {
                  //说明第一步已经完成
                  this.currentMaterialBtnFinished = true
                  this.initCheck()
                }
              }
            } else {
              //已完成
              this.current = ['finished']
              this.searchFinished()
            }

          } else {
            this.$message.warning(res.message)
          }
        })
      }

    }
  }

</script>

<style lang="less" scoped>
  .title {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgb(149, 242, 4);
    height: 100px;
    font-size: 32px;
  }

  .btnFinished {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .box {
    display: flex;
    justify-content: flex-end;
    align-items: flex-end;
  }

</style>